import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Toast } from 'vant'
// 正常加载
import login from '@/views/login'
import index from '@/views/index'
import home from '@/views/index/home'
import ask from '@/views/index/ask'
import video from '@/views/index/video'
import my from '@/views/index/my'
import edit from '@/views/index/edit'
import detail from '@/views/index/detail'
import search from '@/views/index/home/componets/search'
import chat from '@/views/index/my/components/chat.vue'
import results from '@/views/index/home/componets/results.vue'
// _____________________________________________________________________
// 路由懒加载，首屏优化
// 将路由组件的导入方式更改为const 组件名 = ()=>import('路径')
// const login = () => import('@/views/login')
// const index = () => import('@/views/index')
// const home = () => import('@/views/index/home')
// const ask = () => import('@/views/index/ask')
// const video = () => import('@/views/index/video')
// const my = () => import('@/views/index/my')
// const edit = () => import('@/views/index/edit')
// const detail = () => import('@/views/index/detail')
// const search = () => import('@/views/index/home/componets/search')
// const chat = () => import('@/views/index/my/components/chat.vue')
// const results = () => import('@/views/index/home/componets/results.vue')
Vue.use(VueRouter)
const routes = [
  {
    path: '/chat',
    component: chat,
    name: 'chat',
    meta: {
      isNeed: true
    }
  },
  {
    path: '/results',
    component: results,
    name: 'results'
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/detail',
    component: detail,
    name: 'detail'
  },
  {
    path: '/search',
    component: search,
    name: 'search'
  },
  { path: '/login', component: login, name: 'login' },
  {
    path: '/index',
    component: index,
    name: 'index',
    children: [
      {
        path: 'home',
        component: home,
        meta: {
          iskeep: true
        }
      },
      { path: 'ask', component: ask },
      { path: 'video', component: video },
      {
        path: 'my',
        component: my,
        meta: {
          isNeed: true
        }
      }
    ]
  },
  {
    path: '/edit',
    component: edit,
    name: 'edit'
  }
]

const router = new VueRouter({
  routes
})
// 设置守卫导航
router.beforeEach((to, from, next) => {
  // 判断页面是否需要登录，即路由中是否又meta属性
  // to表示去的路由信息,可以理解为点击后的页面路由信息
  // console.log(to)
  // console.log(from)
  if (to.meta.isNeed) {
    // 判断token是否存在
    // 先接收token，获取token,需要先导入store对象
    const token = store.state.token.token
    if (!token) {
      Toast.fail('您还未登录')
      // 携带当前页面的路由跳转到登录页
      router.push(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
